from flask_sqlalchemy import SQLAlchemy
from flask import current_app
from datetime import datetime, timedelta
from sqlalchemy.orm import relationship
from sqlalchemy import Column, Integer, String, Float, DateTime, ForeignKey, Text, JSON, Boolean
import logging
from werkzeug.security import generate_password_hash, check_password_hash

logger = logging.getLogger(__name__)
db = SQLAlchemy()

class User(db.Model):
    __tablename__ = 'users'
    
    id = Column(Integer, primary_key=True)
    user_code = Column(String(50), unique=True)
    username = Column(String(100), nullable=False)
    email = Column(String(120), unique=True, nullable=False)
    phone = Column(String(20))
    membership_level = Column(String(50))
    registration_date = Column(DateTime, default=datetime.utcnow)
    last_login = Column(DateTime)
    consumption_score = Column(Float, default=0)
    status = Column(Boolean, default=True)  # 活跃状态
    segment = Column(String(50))  # 用户分群
    
    orders = relationship('Order', backref='user', lazy=True)
    tags = relationship('UserTag', backref='user', lazy=True)
    
    @property
    def total_consumption(self):
        """计算用户总消费"""
        return sum(order.total_amount for order in self.orders if order.status == 'completed')
    
    @property
    def is_active(self):
        """判断用户是否活跃（90天内有订单）"""
        if not self.orders:
            return False
        latest_order = max(self.orders, key=lambda x: x.order_date)
        days_since_last_order = (datetime.utcnow() - latest_order.order_date).days
        return days_since_last_order <= 90
    
    @property
    def is_churn(self):
        """判断用户是否流失（180天内无订单）"""
        if not self.orders:
            return True
        latest_order = max(self.orders, key=lambda x: x.order_date)
        days_since_last_order = (datetime.utcnow() - latest_order.order_date).days
        return days_since_last_order > 180

class Order(db.Model):
    __tablename__ = 'orders'
    
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    order_date = Column(DateTime, nullable=False, default=datetime.utcnow)
    total_amount = Column(Float, nullable=False)
    status = Column(String(50), default='pending')
    items = Column(JSON)
    
class Tag(db.Model):
    __tablename__ = 'tags'
    
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, nullable=False)
    description = Column(Text)
    category = Column(String(50))
    
class UserTag(db.Model):
    __tablename__ = 'user_tags'
    
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    tag_id = Column(Integer, ForeignKey('tags.id'), nullable=False)
    score = Column(Float, default=0.0)
    last_updated = Column(DateTime, default=datetime.utcnow)
    
    tag = relationship('Tag', backref='user_tags')

class UserSegment(db.Model):
    __tablename__ = 'user_segments'
    
    id = Column(Integer, primary_key=True)
    name = Column(String(100), nullable=False)
    description = Column(Text)
    conditions = Column(JSON)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    is_active = Column(Boolean, default=True)
    
    def apply_conditions(self, user):
        """根据条件判断用户是否属于该分群"""
        if not self.conditions:
            logger.warning("没有设置分群条件")
            return False
            
        logger.info(f"开始应用条件到用户 {user.id}")
        for condition in self.conditions:
            field = condition['field']
            operator = condition['operator']
            value = condition['value']
            
            logger.info(f"处理条件: field={field}, operator={operator}, value={value}")
            
            try:
                if field == 'consumption':
                    user_value = user.total_consumption
                    value = float(value)
                    logger.info(f"消费条件: 用户值={user_value}, 目标值={value}")
                
                elif field == 'checkin_count':
                    user_value = len(user.orders)
                    value = int(value)
                    logger.info(f"入住次数条件: 用户值={user_value}, 目标值={value}")
                
                elif field == 'last_checkin':
                    if not user.orders:
                        logger.info("用户没有订单记录")
                        return False
                    latest_order = max(user.orders, key=lambda x: x.order_date)
                    user_value = (datetime.utcnow() - latest_order.order_date).days
                    value = int(value)
                    logger.info(f"最后入住条件: 用户值={user_value}天前, 目标值={value}天内")
                
                elif field == 'checkin_date_range':
                    if not user.orders:
                        logger.info("用户没有订单记录")
                        return False
                    
                    # 解析日期范围
                    try:
                        start_date = datetime.strptime(value[0], '%Y-%m-%d')
                        end_date = datetime.strptime(value[1], '%Y-%m-%d')
                        logger.info(f"入住时间范围: {start_date} 到 {end_date}")
                        
                        # 检查��户是否有在该时间范围内的订单
                        has_order_in_range = any(
                            start_date <= order.order_date <= end_date
                            for order in user.orders
                        )
                        
                        if not has_order_in_range:
                            logger.info(f"用户 {user.id} 在指定时间范围内没有订单")
                            return False
                            
                        logger.info(f"用户 {user.id} 在指定时间范围内有订单")
                        continue
                        
                    except (ValueError, TypeError) as e:
                        logger.error(f"日期范围格式错误: {e}")
                        return False
                
                elif field == 'membership_level':
                    user_value = user.membership_level
                    logger.info(f"会员等级条件: 用户值={user_value}, 目标值={value}")
                
                else:
                    logger.warning(f"未知的条件字段: {field}")
                    continue
                
                # 应用操作符
                if operator == 'gt':
                    if not user_value > value:
                        logger.info(f"不满足大于条件: {user_value} <= {value}")
                        return False
                elif operator == 'lt':
                    if not user_value < value:
                        logger.info(f"不满足小于条件: {user_value} >= {value}")
                        return False
                elif operator == 'eq':
                    if user_value != value:
                        logger.info(f"不满足等于条件: {user_value} != {value}")
                        return False
                elif operator == 'between' and field != 'checkin_date_range':
                    if not isinstance(value, list) or len(value) != 2:
                        logger.error(f"范围条件值格式错误: {value}")
                        return False
                    start_value, end_value = map(float, value)
                    if not (start_value <= user_value <= end_value):
                        logger.info(f"不满足范围条件: {start_value} <= {user_value} <= {end_value}")
                        return False
                
            except Exception as e:
                logger.error(f"处理条件时出错: {str(e)}")
                return False
                    
        logger.info(f"用户 {user.id} 满足所有条件")
        return True

class Product(db.Model):
    __tablename__ = 'products'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    category = Column(String(20))
    price = Column(Float)

class OrderItem(db.Model):
    __tablename__ = 'order_items'
    id = Column(Integer, primary_key=True)
    order_id = Column(Integer, ForeignKey('orders.id'))
    product_id = Column(Integer, ForeignKey('products.id'))
    quantity = Column(Integer)
    price = Column(Float)
    product = relationship('Product')

class UserActivity(db.Model):
    __tablename__ = 'user_activities'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    activity_type = Column(String(50))
    timestamp = Column(DateTime)
    description = Column(Text)

class Admin(db.Model):
    __tablename__ = 'admins'
    
    id = Column(Integer, primary_key=True)
    username = Column(String(100), unique=True, nullable=False)
    email = Column(String(120), unique=True, nullable=False)
    password_hash = Column(String(200), nullable=False)
    created_at = Column(DateTime, default=datetime.utcnow)
    last_login = Column(DateTime)
    
    def set_password(self, password):
        self.password_hash = generate_password_hash(password)
        
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
